class SessionsController < ApplicationController
  skip_before_action :check_login, :except => [:destroy]


  def login
    @user = User.new
    render layout: nil
  end

  def create
    u = User.valid_users params[:user]
    if u
      session[:user_id] = u.id
      flash[:notice] = '登陆成功！'
      redirect_to root_path
    else
      respond_to do |format|
        format.js {render plain: 'show_error("用户名密码不正确")', layout: nil}
      end
    end

  end

  def destroy
    clear_session
    redirect_to "#{ENV['WFL_URL']}/users/sign_out"
  end

  def failure
    flash[:error] ||= '访问失败！请重新登录或联系系统管理员'
    clear_session
    render layout: nil
  end

  protected
  def init_user(auth)
    h = auth['extra']
    if auth['uid'].blank?
      flash[:notice] = '登陆失败！没有找到用户！'
      return false
    end
    attributes = {
        active: h['available'],
        sso_role_type: h['type_id'],
        name: h['name'],
        login: h['login'],
        school_id: h['school_id'],
        school_ids: h['school_ids'],
        uid: auth['uid'],
        avatar_url: h['avatar_url']
    }
    if user = User.where(uid: auth['uid']).first
      user.update(attributes)
    else
      user = User.create(attributes)
    end
    if user.active?
      user
    else
      flash[:notice] = '登录失败！账户不可用，请联系管理员'
      false
    end
  end
end
